package com.ubxtech.gateway.filter;

import cn.hutool.core.util.IdUtil;
import com.ubxtech.core.context.ContextConstants;
import com.ubxtech.core.context.ContextUtil;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.MDC;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.env.Environment;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import jakarta.annotation.Resource;

/**
 * 添加请求头
 * @author Victor.Xiao
 * @since 2023-08-22 16:47
 **/

@Slf4j
@Component
public class RequestHeaderFilter implements GlobalFilter, Ordered  {

    @Resource
    private Environment environment;
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {

        String traceId = IdUtil.nanoId();
        MDC.put(ContextConstants.X_TRACE_ID, traceId);
        MDC.put(ContextConstants.P_TRACE_ID, traceId);
        ContextUtil.setXTraceId(traceId);
        ContextUtil.setPTraceId(traceId);
        ContextUtil.set(ContextConstants.TRACE_ID, traceId);
        ServerHttpRequest serverHttpRequest = exchange.getRequest().mutate()
//                .headers(h -> h.add(ContextConstants.X_TRACE_ID, ""))
                .headers(h -> {
                    h.add(ContextConstants.P_TRACE_ID, traceId);
                    h.add(ContextConstants.TRACE_ID, traceId);
                    h.add(ContextConstants.HEADER_ORIGIN, environment.getProperty("spring.application.name",""));
                })
                .build();
        ServerWebExchange build = exchange.mutate().request(serverHttpRequest).build();
        return chain.filter(build);
    }

    @Override
    public int getOrder() {
        return Ordered.HIGHEST_PRECEDENCE;
    }
}
